package com.mmy.fta.coldtruck.server.service;

import com.mmy.fta.coldtruck.api.ColdTruckService;
import com.mmy.fta.coldtruck.api.dto.ColdTruckDTO;
import com.mmy.fta.coldtruck.api.dto.ColdTruckTHData;
import com.mmy.fta.coldtruck.api.dto.TruckOrderDTO;
import com.mmy.fta.coldtruck.server.entity.ColdTruckAlarmEntity;
import com.mmy.fta.coldtruck.server.entity.ColdTruckInfoEntity;
import com.mmy.fta.coldtruck.server.entity.ColdTruckOrderEntity;
import com.mmy.fta.coldtruck.server.entity.ColdTruckThRealtimeEntity;
import com.mmy.fta.coldtruck.server.repository.ColdTruckAlarmEntityMapper;
import com.mmy.fta.coldtruck.server.repository.ColdTruckInfoEntityMapper;
import com.mmy.fta.coldtruck.server.repository.ColdTruckOrderEntityMapper;
import com.mmy.fta.coldtruck.server.repository.ColdTruckThRealtimeEntityMapper;
import com.mmy.fta.coldtruck.server.utils.DataUtils;
import com.mmy.fta.usercenter.api.UserService;
import com.ymm.common.rpc.YmmResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author qingyu.meng
 * @date 2021年11月09日 11:08 上午
 * @Description
 */
@Service
@Slf4j
public class ColdTruckServiceImpl implements ColdTruckService {
    @Autowired
    ColdTruckThRealtimeEntityMapper coldTruckThRealtimeEntityMapper;

    @Autowired
    ColdTruckAlarmEntityMapper coldTruckAlarmEntityMapper;

    @Autowired
    ColdTruckOrderEntityMapper coldTruckOrderEntityMapper;

    @Autowired
    ColdTruckInfoEntityMapper coldTruckInfoEntityMapper;

    @Reference
    UserService userService;

    Integer orderId = 320638;


    @Override
    public YmmResult publishColdCargo(ColdTruckDTO coldTruckDTO) {
        if (Objects.isNull(coldTruckDTO)){
            return YmmResult.failResult(000,"参数为空");
        }
        ColdTruckOrderEntity coldTruckOrderEntity = new ColdTruckOrderEntity();

        ArrayList<Double> tarr0  = new ArrayList<>();
        tarr0.add(-100.0);tarr0.add(-22.0);

        ArrayList<Double> tarr1  = new ArrayList<>();
        tarr1.add(-100.0);tarr1.add(-18.0);

        ArrayList<Double> tarr2  = new ArrayList<>();
        tarr2.add(-18.0);tarr2.add(0.0);

        ArrayList<Double> tarr3  = new ArrayList<>();
        tarr3.add(0.0);tarr3.add(10.0);

        ArrayList<Double> tarr4  = new ArrayList<>();
        tarr4.add(10.0);tarr4.add(20.0);

        ArrayList<Double> tarr5  = new ArrayList<>();
        tarr5.add(20.0);tarr5.add(100.0);

        HashMap<Integer, ArrayList<Double>> tMap = new HashMap<>();
        tMap.put(0,tarr0);
        tMap.put(1,tarr1);
        tMap.put(2,tarr2);
        tMap.put(3,tarr3);
        tMap.put(4,tarr4);
        tMap.put(5,tarr5);


        ArrayList<Double> harr0  = new ArrayList<>();
        harr0.add(0.0);harr0.add(50.0);

        ArrayList<Double> harr1  = new ArrayList<>();
        harr1.add(50.0);harr1.add(60.0);

        ArrayList<Double> harr2  = new ArrayList<>();
        harr2.add(65.0);harr2.add(70.0);

        ArrayList<Double> harr3  = new ArrayList<>();
        harr3.add(75.0);harr3.add(85.0);

        ArrayList<Double> harr4  = new ArrayList<>();
        harr4.add(80.0);harr4.add(90.0);

        ArrayList<Double> harr5  = new ArrayList<>();
        harr5.add(85.0);harr5.add(95.0);

        ArrayList<Double> harr6  = new ArrayList<>();
        harr6.add(90.0);harr6.add(95.0);

        ArrayList<Double> harr7  = new ArrayList<>();
        harr7.add(95.0);harr7.add(100.0);

        HashMap<Integer, ArrayList<Double>> hMap = new HashMap<>();
        hMap.put(0,harr0);
        hMap.put(1,harr1);
        hMap.put(2,harr2);
        hMap.put(3,harr3);
        hMap.put(4,harr4);
        hMap.put(5,harr5);
        hMap.put(6,harr6);
        hMap.put(7,harr7);

        coldTruckOrderEntity.setMinAllowTemperature(tMap.get(coldTruckDTO.getTemperature()).get(0));
        coldTruckOrderEntity.setMaxAllowTemperature(tMap.get(coldTruckDTO.getTemperature()).get(1));

        coldTruckOrderEntity.setMinAllowHumidity(hMap.get(coldTruckDTO.getHumidity()).get(0));
        coldTruckOrderEntity.setMaxAllowHumidity(hMap.get(coldTruckDTO.getHumidity()).get(1));

        String route1 = coldTruckDTO.getLoadProvince()+coldTruckDTO.getLoadCity();
        String route2 = coldTruckDTO.getUnloadProvince()+coldTruckDTO.getUnloadCity();
        String route = route1 + " -- " + route2;
        coldTruckOrderEntity.setAlarmType(route);

        coldTruckOrderEntity.setDeparture(coldTruckDTO.getLoadProvince());
        coldTruckOrderEntity.setDestination(coldTruckDTO.getUnloadProvince());

        coldTruckOrderEntity.setCargoId(coldTruckDTO.getCargoId());
        int result = coldTruckOrderEntityMapper.insertSelective(coldTruckOrderEntity);

       /* ColdTruckInfoEntity coldTruckInfoEntity = new ColdTruckInfoEntity();
        coldTruckInfoEntity.setAllowMinTemp(coldTruckOrderEntity.getMinAllowTemperature());
        coldTruckInfoEntity.setAllowMaxTemp(coldTruckOrderEntity.getMaxAllowTemperature());
        coldTruckInfoEntity.setAllowMinHumi(coldTruckOrderEntity.getMaxAllowHumidity());
        coldTruckInfoEntity.setAllowMaxHumi(coldTruckOrderEntity.getMaxAllowHumidity());
        coldTruckInfoEntity.setTruckName(coldTruckOrderEntity.getCargoId());
        int infoResult = coldTruckInfoEntityMapper.insertSelective(coldTruckInfoEntity);*/
      /*  if (infoResult == 0){
            log.info("更新cold_truck_info表失败");
        }*/

        if(result == 0){
            log.info("保存冷运订单温湿度信息失败");
            return YmmResult.failResult(000,"保存冷运订单温湿度信息失败");
        }
        log.info("保存冷运订单温湿度信息成功");
        return YmmResult.succResult();
    }


    @Override
    public YmmResult generateColdTruckOrder(TruckOrderDTO truckOrderDTO) {
        if (Objects.isNull(truckOrderDTO)){
            return  YmmResult.failResult(000,"参数为空");
        }

        int result = coldTruckOrderEntityMapper.updateColdCargoByCargoId(truckOrderDTO.getCargoId(),
                truckOrderDTO.getTruckNo(),
                truckOrderDTO.getDriverName(),
                truckOrderDTO.getOrderNumber());
        if(result == 0){
            return YmmResult.failResult(000,"司机冷运订单温湿度信息失败");
        }

        // todo 插入数据到cold_truck_info表，cargoId存入truck_name
        ColdTruckOrderEntity coldTruckOrderEntity = coldTruckOrderEntityMapper.selectByCargoId(truckOrderDTO.getCargoId());

        ColdTruckInfoEntity coldTruckInfoEntity = new ColdTruckInfoEntity();

        orderId ++;
        coldTruckInfoEntity.setOrderId((long)orderId);

        coldTruckInfoEntity.setTruckName(coldTruckOrderEntity.getCargoId());
        coldTruckInfoEntity.setTruckNo(truckOrderDTO.getTruckNo());

        coldTruckInfoEntity.setMaxTemperature(coldTruckOrderEntity.getMaxAllowTemperature());
        coldTruckInfoEntity.setMinTemperature(coldTruckOrderEntity.getMinAllowTemperature());
        coldTruckInfoEntity.setAverageTemperature((coldTruckOrderEntity.getMaxAllowTemperature()+coldTruckOrderEntity.getMinAllowTemperature())/2);

        coldTruckInfoEntity.setMaxHumidity(coldTruckOrderEntity.getMaxAllowHumidity());
        coldTruckInfoEntity.setMinHumidity(coldTruckOrderEntity.getMinAllowHumidity());
        coldTruckInfoEntity.setAverageHumidity((coldTruckOrderEntity.getMaxAllowHumidity()+coldTruckOrderEntity.getMinAllowHumidity())/2);

        coldTruckInfoEntity.setRoute(coldTruckOrderEntity.getAlarmType());
        coldTruckInfoEntity.setDepature(coldTruckOrderEntity.getDeparture());
        coldTruckInfoEntity.setDestination(coldTruckOrderEntity.getDestination());

        Integer tem = (int)DataUtils.generateRandomRangeDoubleNumber(0.0,100.0);
        coldTruckInfoEntity.setStatus(tem);

        int res = coldTruckInfoEntityMapper.insertSelective(coldTruckInfoEntity);


        log.info("司机-冷运订单温湿度-更新信息成功，车牌号{};插入cold-Truck-info-res：{}",truckOrderDTO.getTruckNo(),res);
        return YmmResult.succResult();
    }

    @Override
    public YmmResult generateTH30Min(String truckNo, Long orderId, Double minTemperature, Double maxTemperature, Double minHumidity, Double maxHumidity, Double minAlarmTemperature, Double maxAlarmTemperature, Double minAlarmHumidity, Double maxAlarmHumidity) {
        return null;
    }

    @Override
    public YmmResult generateTH60Min(String truckNo, Long orderId, Double minTemperature, Double maxTemperature, Double minHumidity, Double maxHumidity, Double minAlarmTemperature, Double maxAlarmTemperature, Double minAlarmHumidity, Double maxAlarmHumidity) {
        return null;
    }

    @Override
    public YmmResult generateRealThData(String truckNo, Long orderId, Double minTemperature, Double maxTemperature
            , Double minHumidity, Double maxHumidity,Double minAlarmTempearture,Double maxAlarmTemperature
            ,Double minAlarmHumidity,Double maxAlarmHumidity) {
        log.info(">>>>>>ColdTruckService:generateRealThData,truckNo is {}<<<<<<");
        for (int i = 0; i < 100; i++) {
            double temperature = DataUtils.generateRandomRangeDoubleNumber(minTemperature, maxTemperature);
            double humidity = DataUtils.generateRandomRangeDoubleNumber(minHumidity, maxHumidity);
            ColdTruckThRealtimeEntity coldTruckThRealtimeEntity = new ColdTruckThRealtimeEntity();
            coldTruckThRealtimeEntity.setOrderId(orderId);
            coldTruckThRealtimeEntity.setTruckNo(truckNo);
            coldTruckThRealtimeEntity.setTemperature(temperature);
            coldTruckThRealtimeEntity.setHumidity(humidity);
            int result = coldTruckThRealtimeEntityMapper.insertSelective(coldTruckThRealtimeEntity);
            if (result == 0){
                log.warn("======ColdTruckService:generateRealThData generate data fail======");
            }

            int alarmResult = 0;
            // 如果温湿度出现超限，将相关信息保存到预警信息表
            if (temperature < minAlarmTempearture){//小于低温预警的温度
                ColdTruckAlarmEntity coldTruckAlarmEntity = new ColdTruckAlarmEntity();
                coldTruckAlarmEntity.setAlarmTemperature(temperature);
                // 低温超限预警
                coldTruckAlarmEntity.setAlarmType(1);
                coldTruckAlarmEntity.setOrderId(orderId);
                coldTruckAlarmEntity.setTruckNo(truckNo);
                result = coldTruckAlarmEntityMapper.insertSelective(coldTruckAlarmEntity);
            }else if(temperature > maxAlarmTemperature){//大于高温预警温度
                ColdTruckAlarmEntity coldTruckAlarmEntity = new ColdTruckAlarmEntity();
                coldTruckAlarmEntity.setAlarmTemperature(temperature);
                // 高温超限预警
                coldTruckAlarmEntity.setAlarmType(2);
                coldTruckAlarmEntity.setOrderId(orderId);
                coldTruckAlarmEntity.setTruckNo(truckNo);
                result = coldTruckAlarmEntityMapper.insertSelective(coldTruckAlarmEntity);
                 }
            if(humidity < minAlarmHumidity){
                ColdTruckAlarmEntity coldTruckAlarmEntity = new ColdTruckAlarmEntity();
                coldTruckAlarmEntity.setAlarmHumidity(humidity);
                // 低湿超限预警
                coldTruckAlarmEntity.setAlarmType(3);
                coldTruckAlarmEntity.setOrderId(orderId);
                coldTruckAlarmEntity.setTruckNo(truckNo);
                result = coldTruckAlarmEntityMapper.insertSelective(coldTruckAlarmEntity);
            }else if(humidity > maxAlarmHumidity){
                ColdTruckAlarmEntity coldTruckAlarmEntity = new ColdTruckAlarmEntity();
                coldTruckAlarmEntity.setAlarmHumidity(humidity);
                // 高湿超限预警
                coldTruckAlarmEntity.setAlarmType(4);
                coldTruckAlarmEntity.setOrderId(orderId);
                coldTruckAlarmEntity.setTruckNo(truckNo);
                result = coldTruckAlarmEntityMapper.insertSelective(coldTruckAlarmEntity);
            }

            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return YmmResult.succResult();
    }

    @Override
    public YmmResult<ColdTruckTHData> paoMaDeng(String cargoId) {
        log.info(">>>>>>ColdTruckService:generateRealThData,cargoId is {}<<<<<<",cargoId);

        ColdTruckInfoEntity coldTruckInfoEntity = coldTruckInfoEntityMapper.selectColdTruckInfo(cargoId);

        ColdTruckTHData coldTruckTHData = new ColdTruckTHData();
        coldTruckTHData.setAverageHumidity(coldTruckInfoEntity.getAverageHumidity());
        coldTruckTHData.setAverageTemperature(coldTruckInfoEntity.getAverageTemperature());
        Double tem1 = coldTruckInfoEntity.getAverageHumidity()+DataUtils.generateRandomRangeDoubleNumber(0.0,0.5);
        tem1 = (double) Math.round(tem1 * 100) / 100;
        coldTruckTHData.setCurrentHumidity(tem1);

        Double temp2 = coldTruckInfoEntity.getAverageTemperature()+DataUtils.generateRandomRangeDoubleNumber(0.0,0.5);
        temp2 = (double) Math.round(temp2 * 100) / 100;
        coldTruckTHData.setCurrentTemperature(temp2);

        return YmmResult.succResult(coldTruckTHData);
    }

    @Override
    public YmmResult alarm(Long orderId,String phoneNumber) {
        log.info(">>>>>>ColdTruckService:alarm,orderId is {}<<<<<<",orderId);
        for (int i = 0; i < 100; i++) {
            List<ColdTruckAlarmEntity> coldTruckAlarmEntities = coldTruckAlarmEntityMapper.selectByOrderId(orderId);
            int size = coldTruckAlarmEntities.size();
            Integer sum = coldTruckAlarmEntities.stream().collect(Collectors.summingInt(ColdTruckAlarmEntity::getAlarmType));

           /* Date beginTime = coldTruckAlarmEntities.get(0).getCreateTime();
            Date endTime = coldTruckAlarmEntities.get(coldTruckAlarmEntities.size() - 1).getCreateTime();*/

            if (sum >= 1 * size && sum < 2 * size){
                userService.sendMessage(phoneNumber,"000001");
                log.warn("低温超限");
            }else if(sum >= 2 * size && sum < 3 * size){
                userService.sendMessage(phoneNumber,"000002");
                log.warn("高温超限");
            }else if(sum >= 3 * size && sum < 4 * size){
                userService.sendMessage(phoneNumber,"000003");
                log.warn("低湿超限");
            }else if(sum == 4){// 高湿超限
                userService.sendMessage(phoneNumber,"000004");
                log.warn("高湿超限");
            }

            // 处理过的数据需要标记
            for (int j = 0; j < coldTruckAlarmEntities.size(); i++) {
                ColdTruckAlarmEntity coldTruckAlarmEntity = coldTruckAlarmEntities.get(j);
                ColdTruckAlarmEntity updateColdTruckAlarmEntity = new ColdTruckAlarmEntity();
                updateColdTruckAlarmEntity.setId(coldTruckAlarmEntity.getId());
                updateColdTruckAlarmEntity.setCount(1L);
                coldTruckAlarmEntityMapper.updateByPrimaryKeySelective(updateColdTruckAlarmEntity);
            }
            try {
                Thread.sleep(60000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


        return YmmResult.succResult();
    }
}
